package com.easywan.inteceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.easywan.pojo.IResult;
import com.easywan.pojo.IResultSupport;
import com.easywan.service.IToolsCounterService;
import com.easywan.service.IToolsNameService;
import com.easywan.util.Utils;
import com.easywan.utils.ToolNamesUtils;
import com.easywan.vo.ToolsName;

import junit.framework.Assert;
import net.sf.json.JSONObject;

@Component
public class CounterInteceptor implements HandlerInterceptor{
	@Autowired
	IToolsNameService toolsNameService;
	
	@Autowired
	IToolsCounterService counterService;
	Logger logger = Logger.getLogger(CounterInteceptor.class);
	
	public void afterCompletion(HttpServletRequest request, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		//counterService = (IToolsCounterService) application.getBean("toolsCounterService");
		try{
			counterToolsClick(request);
			String toolName = request.getRequestURI();
			toolName = ToolNamesUtils.haveIt(toolName);
			if(toolName == null){
				logger.info("没有该工具"+request.getRequestURI());
				return;
			}
			String ip = request.getRemoteAddr();
			Assert.assertNotNull(ip);
			
			//Assert.assertNotNull(toolName);
			logger.info("ip:"+ip + "toolName:"+toolName);
			counterService.add(ip, toolName);
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			endMessage(response,JSONObject.fromObject(IResultSupport.buildResult(IResult.FAILT_CODE, e.getMessage())));
		}
	}

	private void counterToolsClick(HttpServletRequest request) {
		List<ToolsName> tools = toolsNameService.getAll();
		String uri = request.getRequestURI();
		uri = getUri(uri);
		for(ToolsName forTools:tools){
			if(forTools.getUrl().equals(uri)){
				toolsNameService.click(forTools);
				break;
			}
		}
	}

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		
		
		return true;
	}
	public String getUri(String uri){
		if("/introduce/gtd.html".equals(uri)){
			return "/users/work/gtd.html";
		}else{
			return uri;
		}
				
	}
	private void endMessage(HttpServletResponse response, JSONObject fromObject) {
		try {
			PrintWriter w = response.getWriter();
			w.write(fromObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
